#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
#include <iup.h>
#include <iuplua.h>


extern "C" 
{
#include "image.h"
}

void imgWriteSIMTxt(char *filename, Image *img);

int main(void) 
{
  Image *img = imgReadSIM("../resources/F3Inline142.sim");
  if(img != NULL) {
    printf(" %d", img->dcs);
    printf(" %d", img->width);
    printf(" %d\n", img->height);    
    imgWriteSIMTxt("../resources/F3Inline142.txt",img);
  }

  lua_State *L = luaL_newstate ();
  luaL_openlibs (L);
  iuplua_open (L);
  std::string tmp = "main.lua";  
  iuplua_dofile (L, tmp.c_str());
  lua_close (L);


  //system("pause");
  return 0;
}

void imgWriteSIMTxt(char *filename, Image *img)
{
  if(img != NULL) {
    FILE *fp = NULL;
    fp = fopen(filename, "r");
    if (fp != NULL) {
      std::cout << "Arquivo nao exportado: ja existe." << std::endl;
    } else {
      fp = fopen(filename, "w");
      fprintf(fp, "%f\n", (float) img->width);
      fprintf(fp, "%f\n", (float) img->height);
      for(int i = 0; i < img->width; i++) {
        for(int j = 0; j < img->height; j++) {
          fprintf(fp," %f", img->buf[i + j*img->width]);
        }
      }

      //fwrite( img->buf, img->dcs*img->width*img->height, sizeof(float), fp ); // from lower left pixel up to upper wright, by rows 
      std::cout << "Arquivo exportado." << std::endl;
    }
    fclose(fp);
  } else {
    std::cout << "Arquivo nao exportado: Image* m nao inicializado" << std::endl;
  }
}